package com.mall.service.impl;

import com.mall.entity.Order;
import com.mall.entity.Payment;
import com.mall.repository.PaymentRepository;
import com.mall.service.OrderService;
import com.mall.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.UUID;

@Service
public class PaymentServiceImpl implements PaymentService {

    @Autowired
    private PaymentRepository paymentRepository;

    @Autowired
    private OrderService orderService;

    @Override
    public Payment processPayment(Order order, String paymentMethod) {
        // 模拟支付过程
        boolean isSuccess = Math.random() > 0.1; // 90%的成功率

        Payment payment = new Payment();
        payment.setTransactionId(generateTransactionId());
        payment.setOrder(order);
        payment.setPaymentDate(LocalDateTime.now());
        payment.setAmount(order.getTotalAmount());
        payment.setPaymentMethod(paymentMethod);
        payment.setSuccess(isSuccess);

        Payment savedPayment = paymentRepository.save(payment);

        // 更新订单状态
        if (isSuccess) {
            orderService.updateOrderStatus(order.getId(), "PAID");
        }

        return savedPayment;
    }

    private String generateTransactionId() {
        return "TXN-" + UUID.randomUUID().toString().substring(0, 10).toUpperCase();
    }

    @Override
    public Payment getPaymentByTransactionId(String transactionId) {
        return paymentRepository.findByTransactionId(transactionId).orElse(null);
    }

    @Override
    public Payment getPaymentByOrderId(Long orderId) {
        return paymentRepository.findByOrderId(orderId).orElse(null);
    }
}    